﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;

namespace AssignmentsManage.Control
{
    public class LimitedTextBox : TextBox
    {
        ToolTip warningTip;

        #region Overrides

        protected override void OnTextChanged(TextChangedEventArgs e)
        {
            TextChange change = e.Changes.ToList<TextChange>()[0];
            string takeOut = this.Text.Substring(change.Offset, change.AddedLength);
            int selLocation = this.SelectionStart;
            if (takeOut.Contains('>')
                || takeOut.Contains('<')
                || takeOut.Contains('/')
                || takeOut.Contains('"')
                || takeOut.Contains('\''))
            {
                this.Text = this.Text.Remove(change.Offset, change.AddedLength);

                if (selLocation > 0 && selLocation <= this.Text.Length + 1)
                {
                    this.SelectionStart = selLocation - 1;
                }

                if (warningTip != null)
                {
                    warningTip.IsOpen = false;
                }
                warningTip = new System.Windows.Controls.ToolTip();
                warningTip.StaysOpen = false;
                warningTip.Content = "Illegal character.\n(> < \" ' /)";
                warningTip.PlacementTarget = this;
                warningTip.Placement = System.Windows.Controls.Primitives.PlacementMode.Top;
                warningTip.IsOpen = true;
            }

            base.OnTextChanged(e);
        }

        #endregion
    }
}
